package son.nt.act2;

import java.io.BufferedInputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONObject;

import son.nt.R;
import son.nt.common.Contains;
import son.nt.entities.Song;
import son.nt.util.GoogleAnaTool;
import son.nt.util.LogUtil;
import son.nt.util.UtilInterface;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;

public class Act2HttpRequestActivity extends Activity implements OnClickListener{
	private static final String TAG = "Act2HttpRequestActivity";
	private static final String PAGE = "page";
	private static final String QUERY = "query";
	private static final String RESULT = "results";
	private Context mContext;
	ProgressDialog mProgressDialog;
	private boolean isCancel = false;
	private String mJson = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act2_httprequest);
		mContext = this;
		mProgressDialog = new ProgressDialog(mContext);
		GoogleAnaTool.track("Act2HttpRequestActivity");
	}
	
	public void btnOnClick(View v){
		switch (v.getId()) {
		case R.id.btnHttpRequestGetJson:
			new GetJsonLyric().execute("");
			break;
		case R.id.btnHttpRequestInterface:
			testInterfaceUtil();
			break;
		case R.id.btnShowDialog:
			Log.v(TAG, "btnShowDialog click");
			showDialog("Dragon Knight");
			break;
		default:
			break;
		}
	}
	
	public void request(String url){
		try {
			
		} catch (Exception e) {
			Log.e(TAG, "error request : " + e.toString());
		}
	}
	public class GetJsonLyric extends AsyncTask<String, Integer, Integer>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			isCancel = false;
			mProgressDialog.setMessage("waiting...");
			mProgressDialog.show();
			mProgressDialog.setOnCancelListener(new OnCancelListener() {
				
				public void onCancel(DialogInterface dialog) {
					// TODO Auto-generated method stub
					isCancel = true;
				}
			});
		}
		@Override
		protected Integer doInBackground(String... params) {
			try {
				int fileSize = 0;
				String str = "http://192.168.0.103:8080/TicketManager/GetTickets";
//				URL url = new URL(Contains.URL_GETJSON_TWITTER);
				URL url = new URL(str);
				
				HttpURLConnection conn = (HttpURLConnection)url.openConnection();
				if(200 != conn.getResponseCode()){
					Log.v(TAG, "request failse");
					return 0;
				}
				
				Log.v(TAG, "request NOT failse");
//				fileSize = conn.getContentLength();
				Log.v(TAG, "file size:" + fileSize);
				if(0 >= fileSize){
//					Log.v(TAG, "file size <= 0:" + fileSize);
//					return 2;
				}
				 
				
				
				BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
				byte []buf = new byte[1024];
				int len;
				StringBuilder json = new StringBuilder();
				while((len = in.read(buf)) != -1){
					if(!isCancel){
						String s = new String(buf, 0, len);
						
						json.append(s);
					}else{
						in.close();
						return 0;
					}
					mJson = json.toString();
					Log.e("test", "json:" + mJson);
				}
				in.close();
				return 1;
				
			} catch (Exception e) {
				return -1;
			}
			
		}
		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}
		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			int mResult = result;
			mProgressDialog.dismiss();
			if(mResult == 1){
				Handler mHandler = new Handler();
				mHandler.post(new Runnable() {
					
					public void run() {
						LogUtil.toast(mContext, mJson);
//						ContentValues cv = getContentValueFromJson(mJson);
//						Log.v(TAG, "query:" + cv.getAsString(QUERY));
					}
				});
			}
		}
	}
	
	public ContentValues getContentValueFromJson(String json){
		ContentValues cv = new ContentValues();
		try {
			JSONObject jo = new JSONObject(json);
			cv.put(QUERY, jo.getString(QUERY));
			JSONArray jo2 = jo.getJSONArray(RESULT);
			for(int i = 0; i < jo2.length(); i ++){
				JSONObject jo3 = jo2.getJSONObject(i);
				Log.v(TAG, "json array: " + jo3.getString("profile_image_url"));
			}
			
		} catch (Exception e) {
			Log.e(TAG, "err get content value");
			cv = null;
		}
		return cv;
	}
	
	public void testInterfaceUtil(){
		Log.v(TAG, "testInterfaceUtil");
		UtilInterface mUtilInterface = new UtilInterface();
		mUtilInterface.manualSearch("son", listener);
	}
	UtilInterface.ManualSearchListener listener = new UtilInterface.ManualSearchListener() {
		
		public void onGet(Song song) {
			Log.v(TAG, "song title is : " + song.getTitle());
		}
		
		public void onError() {
			Log.e(TAG, "onerror");
		}
	};

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnShowDialog:
			Log.v(TAG, "btnShowDialog click");
//			showDialog("Dragon Knight");
			showDialog(1);
			break;

		default:
			break;
		}
		
	}
	public void showDialog(String msg){
		final Dialog d = new Dialog(Act2HttpRequestActivity.this);
		Window window = d.getWindow();
		window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, 
				WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
		d.setTitle(msg);
		d.setContentView(R.layout.dialog_view);
		TextView txtDialog = (TextView) d.findViewById(R.id.txtDialog);
		txtDialog.setText(msg + " Sonnt");
		Button btn = (Button) d.findViewById(R.id.btnDialogSet);
		btn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				d.dismiss();
			}
		});
		d.show();
	}
	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		final Dialog d = new Dialog(Act2HttpRequestActivity.this);
		String msg = "onCreateDialog";
		Window window = d.getWindow();
		window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, 
				WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
		d.setTitle(msg);
		d.setContentView(R.layout.dialog_view);
		TextView txtDialog = (TextView) d.findViewById(R.id.txtDialog);
		txtDialog.setText(msg + " Sonnt");
		Button btn = (Button) d.findViewById(R.id.btnDialogSet);
		btn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				d.dismiss();
			}
		});
		d.show();
		return d;
		
	}
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		// TODO Auto-generated method stub
		super.onPrepareDialog(id, dialog);
		LogUtil.toast(mContext, "onPrepareDialog");
	}
}
